<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.title"
        placeholder="产品名"
        class="filter-item search-input"
        clearable
        @keyup.enter.native="handleFilter"
      />
      <el-select
        v-model="listQuery.peerId"
        placeholder="所属分公司"
        clearable
        style="width: 190px"
        class="filter-item search-input"
      >
        <el-option v-for="item in peerOptions" :key="item.peerId" :label="item.name" :value="item.peerId" />
      </el-select>
      <el-select
        v-model="listQuery.status"
        placeholder="产品状态"
        clearable
        style="width: 120px"
        class="filter-item search-input"
      >
        <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        添加
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <!--      <el-table-column label="线路ID" width="80px" align="center">-->
      <!--        <template slot-scope="{row}">-->
      <!--          <span>{{ row.ID }}</span>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column label="产品名称" align="center">
        <template slot-scope="{row}">
          <span v-html="row.title"></span>
        </template>
      </el-table-column>
      <el-table-column label="产品价格" align="center">
        <template slot-scope="{row}">
          <span v-html="row.price"></span>
        </template>
      </el-table-column>
      <el-table-column label="返券天数" align="center">
        <template slot-scope="{row}">
          <span v-html="row.ruleDay"></span>
        </template>
      </el-table-column>
      <el-table-column label="返券面值" align="center">
        <template slot-scope="{row}">
          <span v-html="row.ruleTicket"></span>
        </template>
      </el-table-column>
      <el-table-column label="返券次数" align="center">
        <template slot-scope="{row}">
          <span v-html="row.amount"></span>
        </template>
      </el-table-column>
      <el-table-column label="产品状态" align="center">
        <template slot-scope="{row}">
          <el-tag :type="row.status === '已下架' ? 'danger' : (row.status === '草稿' ? 'info' : 'success') ">
            {{ row.status === '草稿' ? '&nbsp;草&nbsp;&nbsp;稿&nbsp;' : row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="所属分公司" align="center">
        <template slot-scope="{row}">
          <span v-html="row.peer" />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center">
        <template slot-scope="{row}">
          <span v-html="row.saleTime"></span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <!--        <template slot-scope="{row,$index}">-->
        <template slot-scope="{row}">
          <el-button size="small" type="primary" icon="el-icon-edit" @click="handleUpdate(row)">编辑</el-button>
          <!--        <el-button size="small" type="danger" plain>删除</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="rigth" label-width="25%">

        <el-form-item label="名称" prop="title">
          <el-input v-model="temp.title" class="window-inp" />
        </el-form-item>
        <el-form-item label="销售价" prop="price">
          <el-input v-model="temp.price" class="window-inp" :readonly="dialogStatus==='update'? true : false "  />
        </el-form-item>
       <el-form-item label="返券频率" >
          <span style="margin-left: 1%;">每</span>
          <el-input v-model="temp.ruleDay" class="window-inp-s" />
          天，返一张券，共返
          <el-input v-model="temp.amount" class="window-inp-s" />
          次
        </el-form-item>
         <div style="width:100%;margin : -2.8% 0 0.5% 0 ;padding-left:25%;font-size:12px;color:#ff4949;line-height:14px">
          <span style="margin: 1% 28% 0 0 ;" id="ruleDaySpan"></span>
          <span style="margin-left: 1%;" id="amountSpan"></span>
        </div>
        
        <el-form-item label="返券面值" prop="ruleTicket">  
          <el-input v-model="temp.ruleTicket" class="window-inp" />
          积分
        </el-form-item>
        <el-form-item label="产品状态" prop="status">
          <el-select v-model="temp.status" placeholder="产品状态" class="window-inp" clearable>
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select> 
        </el-form-item>
        <el-form-item label="分公司" prop="peerId">
          <el-select v-model="temp.peerId" placeholder="分公司" class="window-inp">
            <el-option v-for="item in peerOptions" :key="item.peerId" :label="item.name" :value="item.peerId" />
          </el-select> 
        </el-form-item>
        <el-form-item label="可兑换路线" prop="lineId">
          <el-button class="filter-item line-add" style="" type="primary" icon="el-icon-plus" @click="selectLine()">
            选择线路
          </el-button>
           <el-button class="filter-item line-add"  type="danger" icon="el-icon-delete" @click="delAll()">
            清空线路
          </el-button>
          <input v-model="temp.lineId" type="hidden"/>
          <div class="line-item" ref="lineItem" id="lineItem" >
             <el-table
                    :key="tableKey"
                    :data="editlineList"
                    border
                    fit
                    highlight-current-row
                    :show-header="false"
                    style="width: 100%;">
    
                    <el-table-column label="线路名" >
                      <template slot-scope="{row}">
                        <span>{{ row.title }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column label="操作" align="center" width="35px" fixed="right">
                    <template slot-scope="{row}" >
                      <el-button size="small" type="danger" class = "del-icon" icon="el-icon-delete" @click="delById(row , this)"></el-button>
                    </template>
                  </el-table-column>
                  </el-table>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          {{ $t('table.cancel') }}
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          {{ $t('table.confirm') }}
        </el-button>
      </div>
    </el-dialog>

    <el-dialog title="选择线路" :visible.sync="dialogVisible" width="80%">
      <div class="app-container">
        <div class="filter-container">
          <el-input
            v-model="lineListQuery.title"
            placeholder="线路关键词"
            class="filter-item search-input"
            clearable
            @keyup.enter.native="lineHandleFilter"
          />
          <el-select
            v-model="lineListQuery.status"
            placeholder="线路状态"
            clearable
            style="width: 120px"
            class="filter-item search-input"
          >
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>

          <el-button class="filter-item" type="primary" icon="el-icon-search" @click="lineHandleFilter">
            搜索
          </el-button>
          <el-button class="filter-item" type="primary" @click="defineLine()">
            确定路线选择
        </el-button>
        </div>

        <el-table
          :key="tableKey"
          v-loading="lineListLoading"
          :data="lineList"
          @selection-change="handleSelectionChange"
          ref="lineTable"
          border
          fit
          highlight-current-row
          style="width: 100%;">
          <!--      <el-table-column label="线路ID" width="80px" align="center">-->
          <!--        <template slot-scope="{row}">-->
          <!--          <span>{{ row.ID }}</span>-->
          <!--        </template>-->
          <!--      </el-table-column>-->
          <el-table-column
          type="selection"
          width="55">
        </el-table-column>
          <el-table-column label="线路名" >
            <template slot-scope="{row}">
              <span>{{ row.title }}</span>
            </template>
          </el-table-column>
          <el-table-column label="出发城市" width="100px" align="center">
            <template slot-scope="{row}">
              <span>{{ row.startCity }}</span>
            </template>
          </el-table-column>
          <el-table-column label="目的地" width="100px" align="center">
            <template slot-scope="{row}">
              <span>{{ row.endCity }}</span>
            </template>
          </el-table-column>
          <el-table-column label="金额" width="100px" align="center">
            <template slot-scope="{row}">
              <span style="font-weight :bold;">{{ row.price }}</span>
            </template>
          </el-table-column>
          <el-table-column label="线路状态" width="100px" align="center">
            <template slot-scope="{row}">
              <el-tag :type="row.status === '已下架' ? 'danger' : (row.status === '草稿' ? 'info' : 'success') ">
                {{ row.status === '草稿' ? '&nbsp;草&nbsp;&nbsp;稿&nbsp;' : row.status }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="弱绑定" width="150px" align="center">
            <template slot-scope="{row}">
              <span v-html="row.peer" />
            </template>
          </el-table-column>

        </el-table>

        <pagination
          v-show="lineTotal>0"
          :total="lineTotal"
          :page.sync="lineListQuery.page"
          :limit.sync="lineListQuery.perPage"
          @pagination="getLineList"
        />
      </div>
    </el-dialog>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.perPage"
      @pagination="getList"
    />
  </div>
</template>

<script>
import { list, update, add , lineList , get , lineListById} from '@/api/airDropManagement'
import { listSelection } from '@/api/selectOptions'
import Pagination from '@/components/Pagination'
import $ from 'jquery'

export default {
  components: {
    Pagination
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        title: undefined, // 产品名称
        status: undefined, // 产品状态
        peerId: undefined,
        perPage : 20
        // csv: undefined // 为1时，导出
      },
      temp: {
        id: undefined,
        title: undefined,
        price: undefined,
        ruleDay: undefined,
        amount: undefined,
        status: undefined,
        peer: undefined,
        peerId: undefined,
        ruleTicket: undefined,
        lineId: undefined
      },
      startCityOptions: undefined,
      peerOptions: undefined,
      statusOptions: [{ label: '草稿', value: '0' }, { label: '销售中', value: '1' }, { label: '已下架', value: '2' }],
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增'
      },
      rules: {
          title: [{ required: true, message: '名称不能为空', trigger: 'change' }],
          price: [{ required: true, message: '销售价不能为空', trigger: 'change'},
                  { pattern: /^[1-9]{1}[0-9]*$/, message: '只能输入正整数且开头不能为0', trigger: 'change'}],
          ruleTicket: [{ required: true, message: '返券面值不能为空', trigger: 'change' },
                       { pattern: /^[1-9]{1}[0-9]*$/, message: '只能输入正整数且开头不能为0', trigger: 'change'}],
          ruleDay: [{ required: true, message: '返券天数不能为空', trigger: 'change'},
                  { pattern: /^[1-9]{1}[0-9]*$/, message: '只能输入正整数且开头不能为0', trigger: 'change'}],
          amount: [{ required: true, message: '返券次数不能为空', trigger: 'change' },
                  { pattern: /^[1-9]{1}[0-9]*$/, message: '只能输入正整数且开头不能为0', trigger: 'change'}],
          status: [{ required: true, message: '产品状态不能为空', trigger: 'change' }],
          peerId: [{ required: true, message: '分公司不能为空', trigger: 'change' }],
          lineId: [{ required: true, message: '路线不能为空', trigger: 'change' }],
      },
      dialogVisible: false,
      lineList : undefined,
      lineListQuery : {
        title : undefined ,
        status : undefined,
        peerId : undefined,
        page : 1 ,
        perPage : 20
      },
      lineTotal : 0,
      lineListLoading: true,
      multipleSelection : [],
      editlineList:undefined
    }
  },
  created() {
    this.getPeerOptions()
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      list(this.listQuery).then(response => {
        this.list = response.data
        this.total = response.total
        this.listLoading = false
      })
    },
    getPeerOptions() {
      listSelection().then(response => {
        this.peerOptions = response.data
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleExport() {
      list(Object.assign(this.listQuery, { csv: 1 }), 'arraybuffer').then(response => {
        const content = response
        // 组装a标签
        const elink = document.createElement('a')
        // 设置下载文件名
        elink.download = '附件.csv'
        elink.style.display = 'none'
        const blob = new Blob([content], { type: '.csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel' })
        elink.href = URL.createObjectURL(blob)
        document.body.appendChild(elink)
        elink.click()
        document.body.removeChild(elink)
        this.listQuery.csv = 0
      })
    },
    handleCreate() {
      this.editlineList = [];
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })  
    },
     handleUpdate(row) {
      this.lineListById();
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      get({ ID: row.ID }).then(response => {
        this.temp = Object.assign({}, response.data) // copy obj
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
        this.lineListById(this.temp);
      })
      
    },
    lineListById(data){
      
      if(data != undefined){
        this.lineListQuery.peerId = this.temp.peerId;//
        var ids = data.lineId;
        var idArr = ids.split(",");       
       lineList(this.lineListQuery).then(response => {
        this.lineListQuery.perPage = response.total
        lineList(this.lineListQuery).then(response => {
           var childhtml = "";
           var lines = response.data;
           var editlineList = [];
           for(let i = 0 ; i < idArr.length ; i ++){
             for(let j = 0 ; j < lines.length ; j ++){
               if(idArr[i] == lines[j].ID){
                 editlineList.push(lines[j]);
                 break;
               }
             }
           }
           this.editlineList = editlineList;
        }) 
       })
      }
    },
    resetTemp() {
      this.temp = {
        title: '',
        price: 0,
        ruleDay: '',
        amount: '',
        status: '0',
        peer: '',
        lineId: '',
        peerId: ''

      }
    },
    updateData() {
      var ruleDaybool = false ;
      var regex = /^[1-9]{1}[0-9]*$/;
      var ruleDay = this.temp.ruleDay;
      var amount = this.temp.amount;
      if(ruleDay == "" || ruleDay == null || ruleDay == undefined){
          $("#ruleDaySpan").html("返券天数不能为空");
          $("#ruleDaySpan").show()
          ruleDaybool = false ;
      }else if(!regex.test(ruleDay)){
          $("#ruleDaySpan").html("只能输入正整数且开头不能为0");
          $("#ruleDaySpan").show()
          ruleDaybool = false ;
      }else{
          $("#ruleDaySpan").html("");
          ruleDaybool = true; 
      }
       var amountbool = false ;
      if(amount == "" || amount == null || amount == undefined){
          $("#amountSpan").html("返券次数不能为空");
          $("#amountSpan").show()
          amountbool = false ;
      }else if(!regex.test(amount)){
          $("#amountSpan").html("只能输入正整数且开头不能为0");
          $("#amountSpan").show()
          amountbool = false ;
      }else{
          $("#amountSpan").html("");
          amountbool = true; 
      }
      this.$refs['dataForm'].validate((valid) => {
        if (valid && ruleDaybool && amountbool) {
          update(this.temp).then(response => {
            if (response.code === 200 || response.code === '200') {
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
            } else {
              this.$notify({
                title: '失败',
                message: '更新失败：' + response.msg,
                duration: 2000,
                type: 'error'
              })
            }
          })
          this.getList();
        }
      })
    },
    createData() {
      var ruleDaybool = false ;
      var regex = /^[1-9]{1}[0-9]*$/;
      var ruleDay = this.temp.ruleDay;
      var amount = this.temp.amount;
      if(ruleDay == "" || ruleDay == null || ruleDay == undefined){
          $("#ruleDaySpan").html("返券天数不能为空");
          $("#ruleDaySpan").show()
          ruleDaybool = false ;
      }else if(!regex.test(ruleDay)){
          $("#ruleDaySpan").html("只能输入正整数且开头不能为0");
          $("#ruleDaySpan").show()
          ruleDaybool = false ;
      }else{
          $("#ruleDaySpan").html("");
          ruleDaybool = true; 
      }
       var amountbool = false ;
      if(amount == "" || amount == null || amount == undefined){
          $("#amountSpan").html("返券次数不能为空");
          $("#amountSpan").show()
          amountbool = false ;
      }else if(!regex.test(amount)){
          $("#amountSpan").html("只能输入正整数且开头不能为0");
          $("#amountSpan").show()
          amountbool = false ;
      }else{
          $("#amountSpan").html("");
          amountbool = true; 
      }

      this.$refs['dataForm'].validate((valid) => {
        if (valid && ruleDaybool && amountbool) {
          add(this.temp).then(response => {
            if (response.code === 200 || response.code === '200') {
              this.list.unshift(this.temp)
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 2000
              })
            } else {
              this.$notify({
                title: '失败',
                message: '更新失败：' + response.msg,
                duration: 2000,
                type: 'error'
              })
            }
          })
          this.getList();
        }
        
      })
    },
    delAll(){
      this.temp.lineId = "";
      this.editlineList = []
    },
    
    selectLine() {
      const peerId = this.temp.peerId;
      if(peerId == null || peerId == "" || peerId == undefined){
        this.$notify({
          title: '提示',
          message: '请先选择分公司',
          duration: 2000,
          type: 'error'
        })
        return false;
      }
      this.lineListQuery.peerId = peerId
      this.getLineList();
      this.multipleSelection = [];
    },
    getLineList(){
      this.dialogVisible = true
      lineList(this.lineListQuery).then(response => {
        this.lineList = response.data
        this.lineTotal = response.total
        this.lineListLoading = false
        var lineIds = this.temp.lineId
       this.$nextTick(()=>{
          this.lineList.forEach(row => {
            if(lineIds.indexOf(row.ID) >= 0){
              // this.lineList[i].isCheck = true;
              this.$refs.lineTable.toggleRowSelection(row,true);
            }
          })
        })
      })
    },
    lineHandleFilter() {
      this.lineListQuery.page = 1
      this.getLineList()
    },
    handleSelectionChange(val) {
       this.multipleSelection = val;
    },
    delById(row ,obj){
      $(obj).css("background" , "none");
      for(let i = 0 ; i < this.editlineList.length ; i++ ){
        if(row.ID == this.editlineList[i].ID){
          this.editlineList.splice(i , 1)//删除指定元素
        }
      }
      var lineIds = []
      for(let i = 0 ; i < this.editlineList.length ; i++ ){
          lineIds.push(this.editlineList[i].ID);
      }
      this.temp.lineId = lineIds.join(",")
    },
    defineLine(){
      var ids = "";
      const arr = this.multipleSelection;
      this.editlineList = arr
      for(let i = 0 ; i < arr.length ; i++){
        ids += arr[i].ID + ","
      }
      var str = ids.substring(ids.length - 1 , ids.length);
      if(str == ','){
        this.temp.lineId = ids.substring(0 , ids.length - 1);
      }else{
        this.temp.lineId = ids
      }
      // $("#lineItem").html(childhtml)
      this.dialogVisible = false
    }
  }
}
</script>

<style>
.search-input {
  width: 150px;
  margin-right: 15px;
}

.window-inp {
  width: 50%;
  margin-left: 5%;
  float: left;
  margin: 0 1%;
}

.window-inp-s {
  width: 22%;
  margin: 0 1%;
}

.line-item {
  width: 85%;
  margin-left: 1%;
}

.line-add {
  margin: 0 0 2% 1%;
  padding: 10px 6px;
}
.line-name{
  line-height: 25px;
  background: #9CD5B7;
  width: 99%;
  margin: 0.5% 0.5%;
  float: left;
}
.del-icon{
    color: red;
    float: right;
    cursor: pointer;
    background: none;
    border: none;
    padding: 0px;
}
.del-icon:hover{
  background: none;
  color: red;
}
</style>
